package algotithm.jianzhioffer.test09;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author zhouyanxiang
 * @Date 2020-12-2020/12/13-22:32
 */
public class Solution {

    Deque<Integer> deque1;
    Deque<Integer> deque2;

    public static void main(String[] args) throws Exception {
        Solution solution = new Solution();
        boolean flag = solution.isEmpty();
        System.out.println("the queue is empty ? " + flag);
        solution.push(1);
        flag = solution.isEmpty();
        System.out.println("the queue is empty ? " + flag);
        solution.push(2);
        solution.push(3);
        solution.push(4);
        int x = solution.pop();
        System.out.println("x = " + x);
        int y = solution.pop();
        System.out.println("y = " + y);
        int z = solution.peek();
        System.out.println("z = " + z);
    }

    public Solution() {
        deque1 = new ArrayDeque<>();
        deque2 = new ArrayDeque<>();
    }

    public void copy(Deque<Integer> deque1, Deque<Integer> deque2) {
        while (!deque1.isEmpty()) {
            deque2.push(deque1.pop());
        }
    }

    public void push(int x) {
        deque1.push(x);
    }

    public int pop() {
        copy(deque1, deque2);
        int x = deque2.pop();
        copy(deque2, deque1);
        return x;
    }

    public int peek() throws Exception {
        int x = -1;
        copy(deque1, deque2);
        if (!deque2.isEmpty()) {
            x = deque2.peek();
        } else {
            throw new Exception("the queue is empty");
        }
        copy(deque2, deque1);
        return x;
    }

    public boolean isEmpty() {
        return deque1.isEmpty();
    }
}
